#include <iostream>
#include <thread>
#include <chrono>
#include <functional>
#include <vector>
#include <random>

using namespace std;

// 下载状态
enum class DownloadStatus {
    SUCCESS,
    FAILED,
    CANCELLED
};

// 下载结果
struct DownloadResult {
    string filename;
    DownloadStatus status;
    string filePath;
    int fileSize;
};

// 回调函数类型
using DownloadCallback = function<void(const DownloadResult&)>;

// 模拟下载文件
void downloadFile(const string& url, const string& savePath, DownloadCallback callback) {
    thread([url, savePath, callback]() {
        cout << "开始下载: " << url << endl;
        
        // 模拟下载过程
        random_device rd;
        mt19937 gen(rd());
        uniform_int_distribution<> sizeDist(1024, 1024*1024); // 1KB - 1MB
        uniform_real_distribution<> successDist(0.0, 1.0);
        
        // 模拟网络延迟
        this_thread::sleep_for(chrono::seconds(2));
        
        DownloadResult result;
        result.filename = url.substr(url.find_last_of("/") + 1);
        
        // 模拟90%成功率
        if (successDist(gen) < 0.9) {
            result.status = DownloadStatus::SUCCESS;
            result.filePath = savePath + "/" + result.filename;
            result.fileSize = sizeDist(gen);
            cout << "✓ 下载成功: " << result.filename 
                 << " (" << result.fileSize << " bytes)" << endl;
        } else {
            result.status = DownloadStatus::FAILED;
            result.filePath = "";
            result.fileSize = 0;
            cout << "✗ 下载失败: " << result.filename << endl;
        }
        
        // 调用回调函数通知下载结果
        callback(result);
        
    }).detach();
}

// 实际使用场景
class DownloadManager {
private:
    vector<string> downloadedFiles;
    int successCount = 0;
    int failCount = 0;

public:
    // 回调函数：处理下载成功
    void onDownloadSuccess(const DownloadResult& result) {
        downloadedFiles.push_back(result.filePath);
        successCount++;
        
        // 下载成功后的一系列操作
        cout << "【后续处理】" << endl;
        cout << "  1. 将文件添加到下载列表: " << result.filePath << endl;
        cout << "  2. 更新界面显示" << endl;
        cout << "  3. 发送下载完成通知" << endl;
        cout << "  4. 开始自动病毒扫描..." << endl;
        this_thread::sleep_for(chrono::milliseconds(500));
        cout << "  5. 病毒扫描完成" << endl;
        cout << "  总计成功: " << successCount << " 个文件" << endl << endl;
    }
    
    // 回调函数：处理下载失败
    void onDownloadFailed(const DownloadResult& result) {
        failCount++;
        cout << "【错误处理】" << endl;
        cout << "  1. 记录错误日志: " << result.filename << " 下载失败" << endl;
        cout << "  2. 显示错误提示给用户" << endl;
        cout << "  3. 添加到重试队列" << endl;
        cout << "  总计失败: " << failCount << " 个文件" << endl << endl;
    }
    
    void startBatchDownload() {
        cout << "🚀 开始批量下载文件..." << endl;
        
        // 批量下载多个文件，每个文件使用不同的回调处理
        vector<pair<string, string>> downloads = {
            {"https://example.com/file1.pdf", "./downloads"},
            {"https://example.com/image.jpg", "./downloads"}, 
            {"https://example.com/video.mp4", "./downloads"},
            {"https://example.com/document.doc", "./downloads"}
        };
        
        for (const auto& [url, path] : downloads) {
            downloadFile(url, path, [this](const DownloadResult& result) {
                // 根据下载结果调用不同的处理方法
                if (result.status == DownloadStatus::SUCCESS) {
                    this->onDownloadSuccess(result);
                } else {
                    this->onDownloadFailed(result);
                }
            });
            
            // 主线程继续执行其他任务，不会被下载阻塞
            cout << "主程序可以继续响应用户操作..." << endl;
        }
    }
    
    void showStatistics() {
        cout << "\n📊 下载统计:" << endl;
        cout << "成功: " << successCount << " 个文件" << endl;
        cout << "失败: " << failCount << " 个文件" << endl;
        cout << "下载列表: " << endl;
        for (const auto& file : downloadedFiles) {
            cout << "  - " << file << endl;
        }
    }
};

int main() {
    DownloadManager manager;
    
    cout << "=== 文件下载管理器 ===" << endl;
    manager.startBatchDownload();
    
    // 主线程继续执行，不会被下载阻塞
    cout << "主线程可以处理用户界面事件..." << endl;
    this_thread::sleep_for(chrono::milliseconds(500));
    cout << "主线程可以更新进度条..." << endl;
    this_thread::sleep_for(chrono::milliseconds(500));
    cout << "主线程可以响应按钮点击..." << endl;
    
    // 等待所有下载完成
    this_thread::sleep_for(chrono::seconds(10));
    manager.showStatistics();
    
    return 0;
}